<script setup lang="ts">
import * as echarts from 'echarts'
const props = defineProps({
  //图表配置项
  option: {
    type: Object,
    default() {
      return {}
    },
  },
})
// 获取dom
const el = ref()
let myChart: echarts.ECharts | undefined = undefined
onMounted(() => {
  //初始化chart
  myChart = echarts.init(el.value)
  myChart.setOption(props.option)
})
onBeforeUnmount(() => {
  //解绑事件,销毁chart实例
  window.removeEventListener('resize', resize)
  myChart?.dispose()
})

// 可以直接侦听一个 ref
watch(
  () => props.option,
  async (newVal) => {
    console.log(newVal)
    resize()
    myChart?.setOption(newVal, true)
  }
)
// 监听窗口大小改变,图表自适应
const resize = () => {
  let width = el.value.clientWidth
  let height = el.value.clientHeight
  myChart?.resize({
    width,
    height,
  })
}
</script>

<template>
  <div ref="el" class="js-chart"></div>
</template>

<style lang="scss" scoped>
.js-chart {
  width: 100%;
  height: 100%;
  min-width: 300px;
  min-height: 300px;
}
</style>
